<!-- 实时报警 -->
<script setup>
import { ref, reactive, watch, onMounted, h } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useIuserInfoStore } from '@T2/store/users.ts';
import { buildPositionUnitTree } from '@T2/utils/utils.ts';
import { warnApi as MainApi, warnById as MainById, warnMultiple, unitApi, positionApi } from '@T2/service/api.ts';
import dayjs from 'dayjs';

const iuserInfoStore = useIuserInfoStore();
const { info, getHandleRight } = iuserInfoStore;
const RIGHT = getHandleRight(['383']);

onMounted(() => {
  GetMainTable();
  // getTree();
});

const MainTable = reactive({
  data: [],
  total: 0,
});
const Filter = reactive({
  page: 1,
  pagesize: 30,
  ordering: '-create_time',
  search: '',
  ruletype: null,
  level: null,
});
watch(() => ({...Filter}), (nv, ov) => {
  if (nv.page === 1 || nv.page !== ov.page) {
    GetMainTable();
  } else {
    Filter.page = 1;
  }
});
const GetMainTable = () => {
  MainApi({
    method: 'get',
    params: {
      ...Filter,
      reset_time__isnull: true,
      confirm_user__isnull: true,
    }
  }).then(res => {
    MainTable.data = res?.results || [];
    MainTable.total = res?.count || 0;
  });
}
const levels = { 一: '#32C5FF', 二: '#F7B500', 三: '#FF0000', 四: '#880404',};
const handleMainConfirm = (isAble = false, row) => {
  if (!isAble) {
    return;
  }
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, '您是否要确认此条消息？'),
      h('p',{ style:'font-size:14px;color: #9D9D9D;margin:10px 0;' },'确认后将不再接收此条报警推送消息。'),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    MainById({
      method: 'patch',
      id: row.id,
      data: {
        confirm_user: info.id,
        confirm_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      }
    }).then(res => {
      ElMessage.success('已确认');
      GetMainTable();
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}

/* 回显站点区域 */
const position = reactive({
  tree: [],
  lists: [],
  units: [],
});
const getTree = () => {
  Promise.all([loadUnitList(), getPosition()]).then(res => {
    position.units = res[0];
    position.lists = res[1];
    position.tree = buildPositionUnitTree(res[0], res[1]);
  });
}
const loadUnitList = () => {
  return new Promise((resolve, reject) => {
    unitApi({
      method: 'get',
      params: {},
    }).then(res => {
      resolve(res.results || []);
    }).catch(e => {
      reject(e);
    });
  });
}
const getPosition = () => {
  return new Promise((resolve, reject) => {
    positionApi({
      method: 'get',
      params: {
        ordering: 'id',
      }
    }).then(res => {
      resolve(res.results || []);
    }).catch(e => {
      reject(e);
    });
  });
}
const formatterPosition = (row, column, cellValue, index) => {
  if (!cellValue) {
    return cellValue;
  }
  let text = '';
  let unit = position.units.find(item => item.id === row.unit);
  if (unit?.positon) {
    let position2 = position.lists.find(item => item.id === unit.positon);
    if (position2?.parent) {
      let position1 = position.lists.find(item => item.id === position2.parent);
      text = position1.name + '--' + position2.name;
    }
  }
  return text;
}

/* 显示详情 */
const detailRt = reactive({
  visible: false,
  data: null,
});
const handleMainDetail = (row) => {
  detailRt.visible = true;
  detailRt.data = row;
}

/* 批量操作 */
const mulRt = reactive({
  confirmData: [],
});
const selectionChange = (selected) => {
  mulRt.confirmData = selected;
}
const ConfirmMainMulTable = (isAble = false) => {
  if (!isAble) {
    return;
  }
  let ids = mulRt.confirmData.map(i => i.id);
  ElMessageBox.confirm('', {
    message: h('div', null,[
      h('p',{ style:'font-size:16px;color: #4C4C4C;font-weight:500;'}, '确定要确认勾选的所有报警吗？'),
      h('p',{ style:'font-size:14px;color: #9D9D9D;margin:10px 0;' },'确认后将不再接收这些报警的推送消息。'),
    ]),
    type: 'warning',
    confirmButtonText: '确认',
  }).then(() => {
    warnMultiple({
      method: 'put',
      data: {
        ids,
        update_fileds: {
          confirm_user: info.id,
          confirm_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        },
      }
    }).then(res => {
      ElMessage.success('批量确认成功！');
      GetMainTable();
    });
  }).catch(() => {
    ElMessage.info('已取消');
  });
}
</script>

<template>
  <div class="view flex">
    <div class="alarm-box flex-column mainCard">
      <el-form label-width="120px" class="flex t_form">
        <el-form-item label="报警类型：">
          <el-select v-model="Filter.ruletype" clearable>
            <el-option value="设备故障" label="设备故障"></el-option>
            <el-option value="工艺异常" label="工艺异常"></el-option>
            <el-option value="系统故障" label="系统故障"></el-option>
            <el-option value="通信故障" label="通信故障"></el-option>
            <el-option value="其他故障" label="其他故障"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警等级：">
          <el-select v-model="Filter.level" clearable>
            <el-option value="一" label="一级"></el-option>
            <el-option value="二" label="二级"></el-option>
            <el-option value="三" label="三级"></el-option>
            <el-option value="四" label="四级"></el-option>
          </el-select>
        </el-form-item>
        <div class="flex r_btn">
          <el-button type="primary" @click="ConfirmMainMulTable(RIGHT['383'])" :disabled="!RIGHT['383'] || !mulRt.confirmData.length">
            批量确认
          </el-button>
        </div>
      </el-form>
      <el-table
        :data="MainTable.data"
        scrollbar-always-on
        @selection-change="selectionChange"
      >
        <el-table-column type="selection" fixed="left" width="55" />
        <el-table-column label="报警时间" prop="create_time" min-width="160px" show-overflow-tooltip></el-table-column>
        <el-table-column label="报警设备" prop="device_name" min-width="140px" show-overflow-tooltip></el-table-column>
        <el-table-column label="报警信息" prop="info" min-width="200px"></el-table-column>
        <el-table-column label="报警值" prop="value" align="center" min-width="90px"></el-table-column>
        <el-table-column label="所属站点" prop="unit_name" min-width="140px" show-overflow-tooltip></el-table-column>
        <!-- <el-table-column label="所属区域" prop="unit" min-width="200px" :formatter="formatterPosition" show-overflow-tooltip></el-table-column> -->
        <el-table-column label="报警等级" prop="level" align="center" min-width="90px">
          <template #default="scope">
            <span :style="{color: levels[scope.row.level]}">{{ scope.row.level }}级</span>
          </template>
        </el-table-column>
        <el-table-column label="报警类型" prop="ruletype" min-width="90px"></el-table-column>
        <el-table-column label="当前状态" prop="status" align="center" min-width="120px">
          <template #default="scope">
            <div class="flex-center-center">
              <div class="t-status" v-if="scope.row.reset_time">已恢复</div>
              <div class="t-status noreset" v-else>未恢复</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="100px">
          <template #default="scope">
            <span class="flex-center-center">
              <span style="width: 28px;margin-right: 12px;">
                <template v-if="!scope.row.confirm_time">
                  <el-button link type="primary" @click="handleMainConfirm(RIGHT['383'], scope.row)" :disabled="!RIGHT['383']">
                    确认
                  </el-button>
                </template>
              </span>
              <span style="width: 28px;margin-right: 12px;">
                <el-button link type="primary" @click="handleMainDetail(scope.row)">
                  详情
                </el-button>
              </span>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="->, total, prev, pager, next, sizes"
        background 
        :page-sizes="[10, 20, 30, 50, 100]"
        :pager-count="5"
        v-model:currentPage="Filter.page"
        v-model:page-size="Filter.pagesize"
        :total="MainTable.total"
      />
    </div>
  </div>
  
  <!-- 详情 -->
  <el-dialog width="620px" title="报警详情" v-model="detailRt.visible">
    <div class="detail-body flex-column">
      <div class="flex--center">
        <label style="color: #111111">报警时间：</label>
        <span style="color: #999999">{{ detailRt.data.create_time }}</span>
      </div>
      <div class="flex--center">
        <label style="margin-top: 24px;color: #111111">报警信息</label>
      </div>
      <div class="detail">
        <div class="detail-item flex--center">
          <label>报警设备：</label>
          <p>{{ detailRt.data.device_name }}</p>
        </div>
        <div class="detail-item flex--center">
          <label>报警信息：</label>
          <p>{{ detailRt.data.info }}</p>
        </div>
        <div class="detail-item flex--center">
          <label>所属站点：</label>
          <p>{{ detailRt.data.unit_name }}</p>
        </div>
        <div class="detail-item flex--center">
          <label>报警等级：</label>
          <p :style="{color: levels[detailRt.data.level]}">{{ detailRt.data.level }}级</p>
        </div>
        <div class="detail-item flex--center">
          <label>报警类型：</label>
          <p>{{ detailRt.data.ruletype }}</p>
        </div>
        <div class="detail-item flex--center">
          <label>报警值：</label>
          <p>{{ detailRt.data.value }}</p>
        </div>
        <div class="detail-item flex--center">
          <label>参考值：</label>
          <p>{{ detailRt.data.threshold }}</p>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="detailRt.visible = false">关 闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
@use '@T2/styles/normal.scss';
.view {
  width: 100%;
  height: 100%;
}
.alarm-box {
  flex: 1;
  overflow: hidden;
  position: relative;
}
.t-status {
  position: relative;
  &::before {
    content: '';
    position: absolute;
    left: -14px;
    top: 50%;
    transform: translateY(-50%);
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background-color: #00B42A;
  }
  &.noreset::before {
    background-color: #FF0000;
  }
}

.detail-body {
  padding: 17px 24px;
  .detail {
    padding: 16px 0;
    display: grid;
    gap: 8px;
    grid-template-columns: 1fr 1fr;
    label {
      font-size: 14px;
      color: #999999;
    }
    p {
      font-size: 14px;
      color: #111111;
    }
  }
}
</style>